import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入路由组件 懒加载
const Login = () => import(/* webpackChunkName: "login_home_welcome" */ '../views/login/Login.vue')
const Home = () => import(/* webpackChunkName: "login_home_welcome" */ '../views/home/Home.vue')
const Welcome = () => import(/* webpackChunkName: "login_home_welcome" */ '../views/home/Welcome.vue')

const UserList = () => import(/* webpackChunkName: "UserList_Rights_Roles" */ '../views/user/userList.vue')
const Rights = () => import(/* webpackChunkName: "UserList_Rights_Roles" */ '../views/power/Rights.vue')
const Roles = () => import(/* webpackChunkName: "UserList_Rights_Roles" */ '../views/power/Roles.vue')

const Cate = () => import(/* webpackChunkName: "Cate_CateParams" */ '../views/goods/Cate.vue')
const CateParams = () => import(/* webpackChunkName: "Cate_CateParams" */ '../views/goods/CateParams.vue')

const GoodsList = () => import(/* webpackChunkName: "GoodsList_Add" */ '../views/goods/GoodsList.vue')
const Add = () => import(/* webpackChunkName: "GoodsList_Add" */ '../views/goods/Add.vue')

const Orders = () => import(/* webpackChunkName: "Orders_Report" */ '../views/order/Orders.vue')
const Report = () => import(/* webpackChunkName: "Orders_Report" */ '../views/report/Report.vue')

// 安装路由
Vue.use(VueRouter)
// 配置路由路径
const routes = [
  {
    path:'/',
    redirect:'/login'
  },
  {
    path:'/login',
    component:Login
  },
  {
    // 访问 home 重定向到 welcome 页面
    path:'/home',
    component:Home,
    redirect:'/welcome',
    children:[
      {
        path:'/welcome',
        component:Welcome
      },
      {
        path:'/users',
        component:UserList
      },
      {
        path:'/rights',
        component:Rights
      },
      {
        path:'/roles',
        component:Roles
      },
      {
        path:'/categories',
        component:Cate
      },
      {
        path:'/params',
        component:CateParams
      },
      {
        path:'/goods',
        component:GoodsList
      },
      {
        path:'/goods/add',
        component:Add
      },
      {
        path:'/orders',
        component:Orders
      },
      {
        path:'/reports',
        component:Report
      }
    ]
  }
];
// 创建路由对象
const router = new VueRouter({
  routes,
  mode:'history'
});

// 添加页面的访问权限，配置路由导航守卫 ( beforeEach() )
router.beforeEach((to,from,next) => {
  if(to.path === '/login') return next();
  const tokenStr = window.sessionStorage.getItem('token');
  // 如果有 token 可以访问其他有权限的页面，如果没有 token 就强制访问登录页
  if(!tokenStr) return next('/login');
  next();
})
// 导出路由并挂在路由
export default router
